<template>
  <div>
    <a-modal
      title="菜单分配"
      :visible="visible"
      :confirm-loading="confirmLoading"
      :width="600"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-spin :spinning="loading">
        <a-form-model
          ref="ruleForm"
          :model="formData"
          :rules="rules"
          layout="horizontal"
          labelAlign="left"
          :label-col="{ span: 4 }"
          :wrapper-col="{ span: 20 }"
        >
          <a-form-model-item label="菜单分配">
            <a-tree
              v-model="formData.checkedKeys"
              checkable
              :auto-expand-parent="true"
              :selected-keys="selectedKeys"
              :tree-data="treeData"
              :replaceFields="replaceFields"
              :defaultExpandAll="true"
            />
          </a-form-model-item>
        </a-form-model>
      </a-spin>
    </a-modal>
  </div>
</template>
  <script>
import { setRoleMenuApi, getAllMenuListApi, getRoleDetailApi } from '@/api/manager'
import { listToTree } from '@/utils/util'
export default {
  data() {
    return {
      visible: false,
      confirmLoading: false,
      formData: {
        role_key: '',
        checkedKeys: [], // 菜单
      },
      rules: {
        checkedKeys: [{ required: true, message: '请选择菜单', trigger: 'change' }],
      },
      selectedKeys: [],
      treeData: [],
      replaceFields: {
        children: 'children',
        title: 'name',
        key: 'pkey',
      },
      loading: false,
    }
  },
  created() {
    this.getAllMenuList()
  },
  methods: {
    edit(role_key) {
      this.formData.role_key = role_key
      this.formData.checkedKeys = []
      this.visible = true
      this.getRoleDetail()
    },
    handleOk() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.confirmLoading = true
          const { role_key, checkedKeys } = this.formData
          let arr = []
          let treeData = {
            value: -1,
            children: this.treeData,
          }
          for (let j = 0; j < checkedKeys.length; j++) {
            const item = this.findNodeInTree(treeData, checkedKeys[j], null, 'pkey')
            if (item) {
              arr.push({
                menu_number: item.menu_number,
                menu_name: item.name,
                parent_menu_number: item.parent_menu_number,
              })
            }
          }
          let formObj = {
            role_key,
            menus: arr,
          }
          const { statusCode, errors } = await setRoleMenuApi(formObj)
          this.confirmLoading = false
          if (statusCode == 200) {
            this.visible = false
            this.$message.success('保存成功！')
            this.$emit('success')
            this.$parent.getTableData()
          } else {
            this.$message.error(errors)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleCancel() {
      this.visible = false
    },
    // 获取角色详情
    async getRoleDetail() {
      this.loading = true
      const { data } = await getRoleDetailApi({
        pkey: this.formData.role_key,
      })
      this.loading = false
      let list = data.menus
      let treeData = {
        value: -1,
        children: this.treeData,
      }
      let checkedKeys = []
      for (let i = 0; i < list.length; i++) {
        const item = this.findNodeInTree(treeData, list[i].menu_number, null, 'menu_number')
        if (item) {
          checkedKeys.push(item.pkey)
        }
      }
      this.formData.checkedKeys = checkedKeys
    },
    // 获取用户菜单
    async getAllMenuList() {
      const { data } = await getAllMenuListApi()
      const threeList = listToTree(data, 0)
      this.treeData = threeList
    },
    // 查找树形结构中某一个
    findNodeInTree(tree, targetValue, found = null, str = 'pkey') {
      if (tree[str] == targetValue) {
        return tree
      }
      for (let i = 0; i < tree.children.length; i++) {
        found = this.findNodeInTree(tree.children[i], targetValue, found, str)
        if (found) {
          return found
        }
      }
      return found
    }
  },
}
</script>
      
      <style lang="scss" scoped>
</style>